package com.aaron.kjviewutils.today;

import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aaron.kjviewutils.BaseActivity;
import com.aaron.kjviewutils.R;
import com.aaron.kjviewutils.RecycleViewDividerForList;
import com.aaron.kjviewutils.eventBus.EventBusMsg;
import com.aaron.kjviewutils.retrofit.RetrofitUtil;
import com.bigkoo.pickerview.TimePickerView;
import com.github.ybq.android.spinkit.Style;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Aaron on 2017/3/6.
 */

public class TodayActivity extends BaseActivity {

    @Bind(R.id.todayToolBar)
    Toolbar todayToolBar;
    @Bind(R.id.barTitle)
    TextView barTitle;
    @Bind(R.id.leftBarIcon)
    ImageView leftBarIcon;
    @Bind(R.id.dateTag)
    TextView dateTag;
    @Bind(R.id.choiceDate)
    TextView choiceDate;
    @Bind(R.id.todayRecyclerView)
    RecyclerView todayRecyclerView;

    private List<TodayBean.TodayInner> datas;
    private String dateStr;
    private TodayService todayService;
    private Call<TodayBean> todayCall;
    private TodayAdapter adapter;
    private TimePickerView timePickerView;

    @OnClick(R.id.leftBarIcon)
    void leftBarIconClick()
    {
        closeSelf(TodayActivity.this);
    }

    @OnClick(R.id.choiceDate)
    void choiceDate()
    {
        timePickerView = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
        //控制时间范围
//        Calendar calendar = Calendar.getInstance();
//        pvTime.setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR));//要在setTime 之前才有效果哦
        timePickerView.setTime(new Date());
        timePickerView.setCyclic(false);
        timePickerView.setCancelable(true);
        timePickerView.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date) {
                //设置选择后的日期
                dateStr = obtainToday(date, "MMdd");
                dateTag.setText("历史上的："+obtainToday(date, "MM月dd日"));
                eventBus.post(new EventBusMsg(EventBusMsg.EventBusType.TODAY_CHOICE));
            }
        });
        timePickerView.show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 80)
    public void onEvent(EventBusMsg msg)
    {
        switch (msg.getType())
        {
            case TODAY_CHOICE:
            {
                mHandler.postDelayed(runnableLoadData, 1000);
            }
            break;
            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.layout_today);
        ButterKnife.bind(this);
        initTitle();
        initContent();
    }

    private void initContent()
    {
        datas = new ArrayList<TodayBean.TodayInner>();
        adapter = new TodayAdapter(TodayActivity.this, datas);
        if(TextUtils.isEmpty(dateStr))
        {
            dateStr = obtainToday("MMdd");
            dateTag.setText("历史上的"+obtainToday("MM月dd日"));
        }
        todayRecyclerView.setLayoutManager(new LinearLayoutManager(TodayActivity.this));
        todayRecyclerView.setAdapter(adapter);
        todayRecyclerView.addItemDecoration(new RecycleViewDividerForList(TodayActivity.this, LinearLayout.HORIZONTAL));
        todayRecyclerView.setItemAnimator(new DefaultItemAnimator()); // 默认动画
        mHandler.postDelayed(runnableLoadData, 1000);
    }

    Runnable runnableLoadData = new Runnable() {
        @Override
        public void run() {
            if(null!=progress)
            {
                progress.showProgress(Style.WAVE);
                progress.showAtLocation(todayToolBar, Gravity.CENTER, 0, 0);
            }
            if(null==retrofit)
            {
                retrofit = RetrofitUtil.obtainRetrofit();
            }
            todayService = retrofit.create(TodayService.class);
            todayCall = todayService.obtainTodays(dateStr);
            todayCall.enqueue(new Callback<TodayBean>() {
                @Override
                public void onResponse(Call<TodayBean> call, Response<TodayBean> response) {
                    todayCall.cancel();
                    if(null!=progress)
                    {
                        progress.dismissView();
                    }
                    TodayBean today = response.body();
                    if(null!=today)
                    {
                        if("200".equals(today.retCode))
                        {
                            if(null!=today.result&&!today.result.isEmpty())
                            {
                                datas.clear();
                                datas.addAll(today.result);
                                adapter.notifyDataSetChanged();
                            }
                            else
                            {
                                showMsg("获取数据失败");
                            }
                        }
                        else
                        {
                            showMsg(today.msg);
                        }
                    }
                    else
                    {
                        showMsg("获取数据失败");
                    }
                }

                @Override
                public void onFailure(Call<TodayBean> call, Throwable t) {
                    todayCall.cancel();
                    if(null!=progress)
                    {
                        progress.dismissView();
                    }
                    showMsg("获取数据失败");
                }
            });
        }
    };

    private void initTitle()
    {
        todayToolBar.setTitle("");
        barTitle.setText("历史上的今天");
        loadBackground(leftBarIcon, resources.getDrawable(R.mipmap.back));
        todayToolBar.setNavigationIcon(null);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN)
        {
            //关闭
            closeSelf(TodayActivity.this);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(null!=mHandler)
        {
            mHandler.removeCallbacks(runnableLoadData);
        }
        if(null!=timePickerView)
        {
            timePickerView.dismiss();
        }
        if(null!=todayCall)
        {
            todayCall.cancel();
        }
        ButterKnife.unbind(this);
    }
}
